<?php
/**
 * @version $Id: html.php 1221 2010-05-31 19:00:50Z elkuku $
 * @package    EasyCreator
 * @subpackage Helpers
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath (elkuku) {@link http://www.nik-it.de NiK-IT.de}
 * @author     Created on 06-Mar-2008
 * @license    GNU/GPL, see JROOT/LICENSE.php
 */

//-- No direct access
defined('_JEXEC') or die('=;)');

/**
 * standard HTML stuff...
 * @package		EasyCreator
 */
final class ecrHTML
{
	public $indent = 0;

	/**
	 * Displays a menu based on Joomla! 1.5 Toolbar
	 */
	public static function easyMenu()
	{
		/*   //                                                          //
		 *  //--We start our form HERE ! this is for the whole app !    //
		 * //                                                          //
		 */
		ecrHTML::easyFormStart();

		$task = JRequest::getCmd('task');
		$ecr_project = JRequest::getCmd('ecr_project');

		$project =($ecr_project) ? EasyProjectHelper::getProject($ecr_project) : false;

        //-- Left bar
        $tasks = array();

        $tasks['stuffer'] = new stdClass();
        $tasks['stuffer']->title = JText::_('Project');
        $tasks['stuffer']->image = 'config';
        $tasks['stuffer']->tasks = array('stuffer', 'stufferstuff', 'projectinfo', 'files', 'save_config'
                , 'projectparams', 'projectdelete', 'tables');

        if($project instanceof EasyProject && $project->type != 'package')
        {
            $tasks['languages'] = new stdClass();
            $tasks['languages']->title = JText::_('Languages');
            $tasks['languages']->image = 'ecr_languages';
            $tasks['languages']->tasks = array('languages','translations','searchfiles', 'langcorrectdeforder', 'langcorrectorder', 'show_version'
                    , 'show_versions', 'language_check', 'create_langfile', 'convert');

            $tasks['codeeye'] = new stdClass();
            $tasks['codeeye']->title = JText::_('CodeEye');
            $tasks['codeeye']->image = 'xeyes';
            $tasks['codeeye']->tasks = array('codeeye', 'phpcs', 'phpcpd', 'phpdoc', 'phpunit', 'stats');
        }

        $tasks['ziper'] = new stdClass();
        $tasks['ziper']->title = JText::_('Package');
        $tasks['ziper']->image = 'ecr_archive';
        $tasks['ziper']->tasks = array('ziper', 'ziperzip', 'delete');

        //-- Right bar
        $rightTasks = array();

        $rightTasks['config'] = new stdClass();
        $rightTasks['config']->title = JText::_('ECR_Configuration');
        $rightTasks['config']->image = 'config';
        $rightTasks['config']->tasks = array('config');

		$rightTasks['templates'] = new stdClass();
		$rightTasks['templates']->title = JText::_('Templates');
		$rightTasks['templates']->image = 'wizard';
		$rightTasks['templates']->tasks = array('templates', 'install', 'export');

		$rightTasks['logfiles'] = new stdClass();
		$rightTasks['logfiles']->title = JText::_('Logfiles');
		$rightTasks['logfiles']->image = 'menus';
		$rightTasks['logfiles']->tasks = array('logfiles');

		$rightTasks['help'] = new stdClass();
		$rightTasks['help']->title = JText::_('Help');
		$rightTasks['help']->image = 'help';
		$rightTasks['help']->tasks = array('help', 'quicky', 'credits');

        $rightTasks['sandbox'] = new stdClass();
		$rightTasks['sandbox']->title = JText::_('Sandbox');
		$rightTasks['sandbox']->image = 'default';
		$rightTasks['sandbox']->tasks = array();
		$rightTasks['sandbox']->href = JURI::root().'index.php?option=com_easycreator';
		$rightTasks['sandbox']->class = ' external';
		$rightTasks['sandbox']->js = '';
		$rightTasks['sandbox']->rel = ' target="_blank"';

		//--Menu highlighting... set css class _active
		$actives = array();
		$rTasks = array();

		foreach($tasks as $k=>$v)
		{
			$actives[$k]=(in_array($task, $v->tasks)) ? 'active' : '';
		}

		foreach($rightTasks as $k=>$v)
		{
			$actives[$k] = (in_array($task, $v->tasks)) ? 'active' : '';
			$rTasks = array_merge($rTasks, $v->tasks);
		}

		$js = 'onchange="submitbutton(\''.$task.'\')"';
		?>
		<div class="white_box" style="margin-bottom: 0.5em;">
		<?php self::boxStart(); ?>
        <div class="ecr_easy_toolbar">
            <ul>
                <li>
                    <a href="javascript:;" onclick="$('file_name').value=''; easySubmit('jhelp', 'help');">
                        <span class="icon-32-JHelp_btn" title="J Help"></span>
                        J! API
                    </a>
                </li>
            </ul>
        </div>
        <?php echo(ECR_DEBUG) ? '<div class="debug_ON">Debugging</div>' : ''; ?>
        <div style="float: left; margin-top: -10px;">
		   <img src="<?php echo JURI::Root(); ?>administrator/components/com_easycreator/assets/images/easylogo_t.png" alt="Easy-Joomla Logo"/>
		</div>
        <div style="float: left; padding-left: 0.5em;">
            <span style="font-size: 1.4em; font-weight: bold;">EasyCreator</span>
        <span id="ecr_stat_project"></span>
            <br />
            <?php self::drawProjectSelector(); ?>
		</div>
        <div style="float: left;">
            <?php
            if( $ecr_project
             && $ecr_project != 'ecr_new_project'
             && $ecr_project != 'ecr_register_project'
              )
            {
                ?>
                <div class="ecr_easy_toolbar">
                <ul>
                <?php
#                <li class="divider"></li>
                foreach($tasks as $k => $v)
                {
                    ?>
                    <li class="<?php echo $actives[$k]; ?>">
                        <?php
                        echo '<a href="javascript:;" onclick="$(\'file_name\').value=\'\'; easySubmit(\''.$k.'\', \''.$k.'\');">';
                        echo '<span class="icon-32-'.$v->image.'" title="'.$v->title.'"></span>';
                        echo $v->title.NL;
                        echo '</a>';
                        ?>
                    </li>
                    <?php
                }//foreach
                ?>
                </ul>
                </div>
                <?php
            }//endif
            ?>
    	</div>
    	<?php
		if( ! in_array($task, $rTasks))
		{
		?>
			<a href="javascript:;" style="float: left; margin-left: 5px;" class="ecr_button img icon-16-add hasTip" title="<?php echo JText::_('More'); ?>::<?php echo JText::_('Click for more options'); ?>" onclick="this.setStyle('display', 'none'); ecr_options_box.toggle();">
				<?php echo JText::_('More').'...' ?>
			</a>
		<?php
		}
		$stdJS = '';
		$stdJS .= "$('adminForm').value='';";
		$stdJS .= "$('file_name').value='';";
		?>
		<div id="ecr_options_box" style="float: left; padding-left: 0.5em;">
			<div class="ecr_easy_toolbar">
                <ul>
                <li class="divider"></li>
                    <?php
                    foreach($rightTasks as $k => $v)
                    {
                        $controller =(isset($v->controller)) ? $v->controller : $k;
                        $cJS = " easySubmit('".$k."', '".$controller."');";
                        $class =(isset($v->class)) ? $v->class : '';
                        $href =(isset($v->href)) ? $v->href : 'javascript:;';
                        $rel =(isset($v->rel)) ? $v->rel : '';
                        $js =(isset($v->js)) ? $v->js : 'onclick="'.$stdJS.$cJS.'"';
                        ?>
                        <li class="<?php echo $actives[$k]; ?>">
                        <?php
                        echo '<a href="'.$href.'" '.$js.$rel.' class="'.$class.'">'.NL;
                        echo '<span class="icon-32-'.$v->image.'" title="'.$v->title.'"></span>'.NL;
                        echo $v->title.NL;
                        echo '</a>'.NL;
                        ?>
                        </li>
                        <?php
                    }//foreach
                    ?>
			    </ul>
            </div>
		</div>
		<?php
        /*
         * J1.6 Alpha testing warning
         */
        if(version_compare(JVERSION, '1.6', '>='))
        {
            echo '<strong style="color: red; padding: 2em;">ALPHA TESTING on Joomla! 1.6!</strong>';
        }

		?>

		<?php
		if( ! in_array($task, $rTasks))
		{
		?>
			<script type="text/javascript">
				var ecr_options_box = new Fx.Slide('ecr_options_box');
				ecr_options_box.hide();
			</script>
		<?php
		}
		?>

		<div style="clear: both"></div>
		<?php
		self::boxEnd();
		?>
		</div>
		<?php
	}// function

	/**
	 * draws a checkbox
	 * select if a backup version should be saved
	 */
	public static function chkVersioned()
	{
		$params = &JComponentHelper::getParams('com_easycreator');
		$save_versioned = JRequest::getInt('save_versioned', $params->get('save_versioned'));
		$checked =($save_versioned) ? ' checked="checked"' : '';
		$html = '<input type="checkbox" name="save_versioned" id="save_versioned" value="1"'.$checked.'><label for="save_versioned">'.JText::_('Save versioned').'</label>';
		return $html;
	}//function

	/**
	 * draws a checkbox
	 * select if the file remains open afer save
	 */
	public static function chkGoonEdit()
	{
		$params = &JComponentHelper::getParams('com_easycreator');
		$goon_edit = JRequest::getInt('goon_edit', $params->get('goon_edit'));
		$checked =($goon_edit) ? ' checked="checked"' : '';

		$html = '';
		$html .= '<input type="checkbox" name="goon_edit" id="goon_edit" value="1"'.$checked.' />';
		$html .= '<label for="goon_edit">'.JText::_('Continue editing').'</label>';
		echo $html;
	}//function

	/**
	 * Draws a fileselector
	 *
	 * @param string $pathToDir path to directory
	 * @param string $task task for javascript
	 * @return void
	 */
	public static function drawFileSelector($pathToDir, $task)
	{
		if( ! $pathToDir || ! is_dir($pathToDir))
		{
			return JText::_('invalid path');
		}

		//--just for highlighting
		$the_file = JRequest::getVar('file', NULL);

		//--get the file list
		$files = JFolder::files($pathToDir);

		echo  NL.'<div id="ecr_filebutton">';
		echo NL.'<ul>';
		foreach($files as $file)
		{
			$style = '';
			if( $file == $the_file )//highlight ?
			{
				$style = ' style="color: red; font-weight: bold;"';
			}
			echo NL.'<li><a '.$style.'href="#" onclick="document.adminForm.file.value=\''.$file.'\'; submitbutton(\''.$task.'\');">'.$file.'</a></li>';
		}
		echo NL.'<ul>';
		echo NL.'</div>';
	}// function

	/**
	 * Draws a minibutton
	 *
	 * @param string $img
	 * @param string $title
	 * @param string $task
	 * @param string $javascript
	 */
	public static function drawMiniButton($img, $title, $task, $javascript = '')
	{
		$js =($javascript) ? $javascript : 'onclick="javascript: submitbutton(\''.$task.'\')"';
		echo NL.'<a href="#" class="toolbar" '.$js.'>';
		echo NL.'<span class="icon-32-'.$img.'" title="'.$title.'"></span>';
		echo NL.$title;
		echo NL.'</a>';
	}// function

	public static function drawButtonCreateLanguageFile($lang, $scope)
	{
		$button = '<span class="ecr_button img icon-16-add" ';
		$button .= 'onclick="document.adminForm.lngcreate_lang.value=\''.$lang.'\'; ';
		$button .= 'document.adminForm.scope.value=\''.$scope.'\'; ';
		$button .= 'submitform(\'create_langfile\');">'.JText::_('Create language file').'</span>';
		echo $button;
#        self::displayMessage(array(JText::_('File not found'), $button));
	}//function

	public static function drawButtonRemoveBOM($fileName)
	{
		$tPath = substr($fileName, strlen(JPATH_ROOT));
		$link = 'See: <a href="http://www.w3.org/International/questions/qa-utf8-bom" target="_blank">W3C FAQ: Display problems caused by the UTF-8 BOM</a>';
		$button = '<br /><span class="ecr_button img icon-16-delete" onclick="document.adminForm.file.value=\''.addslashes($tPath).'\';easySubmit(\'remove_bom\', \'languages\');">Remove BOM</span>';
		self::displayMessage(array(JText::_('Found a BOM in languagefile'), $fileName, $link, $button), 'notice');
	}//function

	public static function drawButtonCreateClassList()
	{
		$button = '<br /><span class="ecr_button img icon-16-add" ';
		$button .= 'onclick="create_class_list();">'.JText::_('Create class list file').'</span>';
		self::displayMessage(array(JText::sprintf('The class file for your Joomla version %s has not been build yet.', JVERSION), $button), 'notice');
	}//function

	/**
	 * Draws the standard footer
	 *
	 */
	public static function footer()
	{
		$version = '';
		$version .='<strong style="color: green;">'.ECR_VERSION.'</strong>';
        $version .=(strpos($version,'SVN')) ? ' <span style="color:red;">Rev. # '.ecrHTML::getVersionFromCHANGELOG('com_easycreator').'</span>' : '';
		?>
		<div class="ecrFooter">
			EasyCreator <?php echo $version; ?> runs best on <a href="http://www.mozilla-europe.org/firefox/" class="external">Firefox</a> and <a href="http://opensuse.org" class="external">openSUSE</a>
			<br />Made and partially Copyright &copy; 2008 - 2010 by <span class="img icon-16-easy-joomla"><a href="http://easy-joomla.org"  class="external">Easy-Joomla.org</a></span>
			<br />
			<small><em style="color: silver;">This product is not affiliated with or endorsed by the Joomla! Project. It is not supported or warranted by the Joomla! Project or Open Source Matters. The Joomla! logo is used under a limited license granted by Open Source Matters the trademark holder in the United States and other countries.</em></small>
		</div>
		<?php

		if(defined('ECR_DEBUG') && ECR_DEBUG ) { ecrDebugger::printSysVars('get'); ecrDebugger::printSysVars('post');}

		echo NL.'<!-- EasyCreator END -->'.NL;
	}// function

	/**
	 * Draws a h1 tag with title and project name.
	 *
	 * @param string $title
	 * @param object $project EasyProject
	 */
	public static function header($title, EasyProject $project)
	{
		$pName = $project->name;
		$pType = ucfirst($project->type);

		$html = '';
		$html .= $title;
		$html .=($pType) ? '&nbsp;<span style="color: black">'.JText::_($pType).'</span>' : '';
		$html .=($pName) ? '&nbsp;<span style="color: green">'.$pName.'</span>' : '';

		echo '<h1>'.$html.'</h1>';
	}//function

	/**
	 * This will write the 'opening' tags for our form.
	 * we also provide an id tag - as the name tag will be deprecated..
	 */
	public static function easyFormStart()
	{
		?>
		<!-- EasyCreator START -->

		<div id="ecr_box">

		<form action="index.php" method="post" name="adminForm" id="adminForm">
		<?php
	}// function

	/**
	 * This will write the 'closing' tags for our form
	 */
	public static function easyFormEnd($closeDiv = true)
	{
	?>
		<input type="hidden" name="<?php echo JUtility::getToken(); ?>" value="1" />
		<input type="hidden" name="option" value="com_easycreator" />
		<input type="hidden" name="task" value="" />
		<input type="hidden" name="controller" value="<?php echo JRequest::getCmd('controller'); ?>" />
		<input type="hidden" name="view" value="<?php echo JRequest::getCmd('view'); ?>" />

		<input type="hidden" name="file_name" id="file_name" value="<?php echo JRequest::getVar('file_name'); ?>" />
		<input type="hidden" name="file_path" id="file_path" value="<?php echo JRequest::getVar('file_path'); ?>" />
	</form>
	<?php if($closeDiv): ?>
	</div>
	<?php endif; ?>
	<div style="clear: both"></div>
	<?php
	}// function

	/**
	 * Display options for logging
	 */
	public static function drawLoggingOptions()
	{
		$buildopts = array(
			 'files' => JText::_('Log file contents')
			, 'profile'	=> JText::_('Profile')
		);

		//--Get component parameters
		$params =& JComponentHelper::getParams('com_easycreator');

		echo NL.'<div class="logging-options">';

		$js = "v =( $('div_buildopts').getStyle('display') == 'block') ? 'none' : 'block';";
		$js .= "$('div_buildopts').setStyle('display', v);";

		$checked =($params->get('logging')) ? ' checked="checked"' : '';
		echo NL.'<input type="checkbox" onchange="'.$js.'" name="buildopts[]"'.$checked.' value="logging" id="logging" />';
		echo NL.'<label for="logging">'.JText::_('Activate logging').'</label>';

		$style =($params->get('logging')) ? '' : ' style="display: none;"';
		echo NL.'   <div id="div_buildopts"'.$style.'>';
		foreach( $buildopts as $name=>$titel )
		{
			//--Get component parameters
			$checked =($params->get($name)) ? ' checked="checked"' : '';

			echo NL.'&nbsp;|__';
			echo NL.'<input type="checkbox" name="buildopts[]"'.$checked.' value="'.$name.'" id="'.$name.'" />';
			echo NL.'<label for="'.$name.'">'.$titel.'</label><br />';
		}//foreach
		echo NL.'   </div>';
		echo NL.'</div>';
	}// function

	/**
	 * Display options for packing format
	 */
	public static function drawPackOpts($projectParams = array())
	{
		//--Get component parameters
		$params =& JComponentHelper::getParams('com_easycreator');

		$formats = array(
			  'archive_zip' => 'zip'
			, 'archive_tgz' => 'tgz'
			, 'archive_bz2' => 'bz2'
		);

		$opts = array();

		foreach($formats as $name => $ext)
		{
			if(isset($projectParams[$name]))
			{
			    $opts[$name] =($projectParams[$name] == 'ON') ? true : false;
			}
			else
			{
			    $opts[$name] =($params->get($name) == 'on') ? true : false;
			}
		}//foreach

        if( ! $opts['archive_zip']
         && ! $opts['archive_tgz']
         && ! $opts['archive_bz2']
         )
        {
            ecrHTML::displayMessage(JText::_('Please set a compression type'), 'notice');
            echo '<div style="float: right;">'.JHTML::tooltip(JText::_('You can set a default compression type in configuration')).'</div>';
        }

		foreach($formats as $name => $ext)
		{
			$checked =($opts[$name]) ? ' checked="checked"' : '';

			echo NL.'<div align="left">';
			echo NL.'   <input type="checkbox" name="buildopts[]"'.$checked.' value="'.$name.'" id="'.$name.'" />';
			echo NL.'   <label for="'.$name.'">'.$ext.'</label>';
			echo NL.'</div>';
		}//foreach
	}// function

	/**
	 * Load the great code editor EditArea.
	 *
	 *       **************
	 *       ** EditArea **
	 *       **************
	 * CFG:
	 * path		- to EditArea file
	 * type		- EditArea file name
	 * form		- name
	 * textarea	- name
	 * syntax	- for highlighting
	 */
	public static function loadEditArea($cfg)
	{
		JFactory::getDocument()->addScript(JURI::root(true).$cfg['path'].'/'.$cfg['type']);

		$translates = array('txt');
		if(in_array($cfg['syntax'], $translates))
		{
			$cfg['syntax'] = 'brainfuck';
		}
		?>

		<!-- **************** -->
		<!-- ****  load  **** -->
		<!-- *** EditArea *** -->
		<!-- **************** -->
		<script language="javascript" type="text/javascript">
			editAreaLoader.init({
				id : "<?php echo $cfg['textarea']; ?>"
				,syntax: "<?php echo $cfg['syntax']; ?>"
				,start_highlight: true
				,replace_tab_by_spaces: 3
				,end_toolbar: 'html_select, autocompletion'
				,plugins: "html, autocompletion"
				,autocompletion: 'true'
				,font_size: 8
				<?php echo(ECR_DEBUG) ? ",debug: true\n" : ''; ?>
			});

			function save_file(pressbutton, id)
			{
				url = '';
				url = 'index.php?option=com_easycreator&tmpl=component&format=raw';
				url += '&controller=stuffer&task=save';

				code = encodeURIComponent(editAreaLoader.getValue('<?php echo $cfg['textarea']; ?>'));

				post = '';
				post += 'file_path='+$('file_path').value;
				post += '&file_name='+$('file_name').value;
				post += '&c_insertstring='+ code;

				var box = $('ecr_status_msg');
			    var fx = box.effects({duration: 1000, transition: Fx.Transitions.Quart.easeOut});

				new Ajax( url,
						{
                    'onRequest': function()
                        {
                            oldTitle = $('ecr_title_file').innerHTML;
                            oldClass = $('ecr_title_file').className;
            		        $('ecr_title_file').innerHTML = 'Saving...';
            		        $('ecr_title_file').className = oldClass+' ajax_loading16-red';

                        },
                    'onComplete': function(request)
                        {
            				$('ecr_title_file').innerHTML = oldTitle;
            				$('ecr_title_file').className = oldClass;
            				box.setHTML(request);
            				box.style.display="inline";
                        	fx.start({
                        	}).chain(function() {
                        	this.start.delay(1000, this, {'opacity' : 0});
                        	}).chain(function() {
                        	box.style.display="none";
                        	this.start.delay(0100, this, {'opacity' : 1});
                        	});
                        }
		         }).request(post);
			}//function
		</script>
		<?php
	}//function

	/**
	 * Loads the file tree and adds the required css and js.
	 *
	 * @return void
	 */
	public static function initFileTree()
	{
		ecrLoadHelper('php_file_tree');

		//-- Add css
		ecrStylesheet('php_file_tree');

		//-- Add javascript
		ecrScript('php_file_tree');
	}//function

	/**
	 *
	 * @return void
	 */
	public static function prepareFileEdit()
	{
		$config = JComponentHelper::getParams('com_easycreator');

		$fieldId = 'ecr_code_area';

		$editarea_type = $config->get('editarea_type', 'edit_area_full.js');

		//-- Load EditArea code editor
		$editAreaVersion = '0_8_1_1';
		ecrHTML::loadEditArea( array(
			'path'		=> '/administrator/components/com_easycreator/assets/js/editarea_'.$editAreaVersion,
			'type'		=> $editarea_type,
			'syntax'	=> '',
			'form'		=> 'adminForm',
			'textarea'	=> $fieldId
		));
		?>
		<div id="sld_picture">
			<br />
			<span class="ecr_title_file" id="ecr_title_pic">
				<?php echo JText::_('Select a file'); ?>
			</span>
			<br />
			<br />
			<div id="container_pic" style="height: 100%; background-color: #ffffff; border: 1px solid grey;">
			</div>
		</div>
		<div id="sld_edit_area">
			<div style="float: right; margin-top: 10px;">
			    <span id="ecr_status_msg"></span>
				<span class="ecr_button img icon-16-save" onclick="save_file('save');">
				   <?php echo JText::_('Save'); ?>
				</span>
			</div>
			<br />
			<span class="ecr_title_file" id="ecr_title_file">
				<?php echo JText::_('Select a file'); ?>
			</span>
			<div style="clear: both; padding-bottom: 0.5em;">
			</div>

    		<textarea id="<?php echo $fieldId; ?>" name="c_insertstring" style="height: 500px; width: 100%;"></textarea>
    		<input type="hidden" name="old_task" value="<?php #echo $task; ?>" />
		</div>
		<script>
			var sld_edit_area = new Fx.Slide('sld_edit_area');
			var sld_picture = new Fx.Slide('sld_picture');
			sld_picture.hide();
		</script>
		<?php
	}//function

	/**
	 * Extract strings from svn:property Id
	 *
	 * @param string $path full path to CHANGELOG.php
	 * @param bool $revOnly true to return revision number only
	 * @return string/bol propertystring or FALSE
	 * like:
	 * @ version $I d: CHANGELOG.php 362 2007-12-14 22:22:19Z elkuku $
	 * [0] => Id: [1] => CHANGELOG.php [2] => 362 [3] => 2007-12-14 [4] => 22:22:19Z [5] => elkuku [6] => ;)
	 */
	public static function getVersionFromCHANGELOG($appName, $revOnly = false)
	{
		// TODO change to getVersionFromFile

		$file = JPATH_ADMINISTRATOR.DS.'components'.DS.$appName.DS.'CHANGELOG.php';
		if( ! file_exists($file)) { return false; }

		//--we do not use JFile here cause we only need one line which is
		//--normally at the beginning..
		$f = fopen($file, 'r');
		$ret = false;

		while($line = fgets($f, 1000))
		{
			if(strpos($line, '@version'))
			{
				$line = explode('$', $line);
				$line = explode(' ', $line[1]);
				$svn_rev = $line[2];
				$svn_date = date("d-M-Y", strtotime($line[3]));
				$ret = $svn_rev;
				$ret .=($revOnly) ? '' : '  / '.$svn_date;

				break;
			}
		}// while

		fclose($f);

		return $ret;
	}// function

	/**
	 * Wizard
	 * Displays the project information introduced so far.
	 *
	 * @param JObject $project
	 * @param array $formFieldNames fields already displayed
	 */
	public static function displayResult(EasyProject $project, $formFieldNames = array())
	{
	    ecrLoadHelper('easytemplatehelper');

		?>
		<div class="ecr_result">
			<h3><?php echo JText::_('Your extension so far'); ?></h3>

		  <?php
			ecrHTML::displayResultFieldRow(JText::_('Type'), 'type', 'tpl_type', $project, $formFieldNames);
            ecrHTML::displayResultFieldRow(JText::_('Template'), 'tplName', 'tpl_name', $project, $formFieldNames);
            ecrHTML::displayResultFieldRow(JText::_('JVersion'), 'JCompat', 'jcompat', $project, $formFieldNames);

			echo '<div style="background-color: #fff; border: 1px solid gray; padding-left: 0.5em;">';
            if( $info = easyTemplateHelper::getTemplateInfo($project->type, $project->tplName))
            {
                echo $info->description;
            }
			echo '</div>';

            echo '<div class=extension" style="background-color: #ffff99; padding: 1em; font-size: 1.2em;">';
			ecrHTML::displayResultFieldRow(JText::_('Name'), 'name', 'com_name', $project, $formFieldNames);
			ecrHTML::displayResultFieldRow(JText::_('Version'), 'version', 'version', $project, $formFieldNames);
			ecrHTML::displayResultFieldRow(JText::_('Description'), 'description', 'description', $project, $formFieldNames);
		    echo '</div>';

            echo '<div class="credits" style="background-color: #ffc;">';
		    ecrHTML::displayResultFieldRow(JText::_('Author'), 'author', 'author', $project, $formFieldNames);
			ecrHTML::displayResultFieldRow(JText::_('Author e-mail'), 'authorEmail', 'authorEmail', $project, $formFieldNames);
			ecrHTML::displayResultFieldRow(JText::_('Author URL'), 'authorUrl', 'authorUrl', $project, $formFieldNames);
			ecrHTML::displayResultFieldRow(JText::_('License'), 'license', 'license', $project, $formFieldNames);
			ecrHTML::displayResultFieldRow(JText::_('Copyright C'), 'copyright', 'copyright', $project, $formFieldNames);

	#		echo '<div class="img icon-16-easy-joomla">AutoCode</div>';
			ecrHTML::displayResultFieldRow(JText::_('List postfix'), 'listPostfix', 'list_postfix', $project, $formFieldNames);

			echo '</div>';
			?>
		</div>
		<?php
	}//function

	/**
	 * Wizard form
	 * displays a table row with a hidden formfield if not included in $formFieldNames
	 *
	 * @param string $title
	 * @param string $property
	 * @param string $formFieldName
	 * @param object $project
	 * @param array $formFieldNames fields not to display
	 */
	private static function displayResultFieldRow($title, $property, $formFieldName, EasyProject $project, $formFieldNames)
	{
		if( ! $project->$property)
		{
		    return;
		}
	    ?>
	    <div class="ecr_table-row">
    	    <div class="ecr_table-cell" style="width: 25%; font-weight: bold;">
    			<?php echo $title; ?>
    	    </div>
    	    <div class="ecr_table-cell">
    			<?php echo $project->$property; ?>
    				<?php if( ! in_array($formFieldName, $formFieldNames)) : ?>
    					<input type="hidden" name="<?php echo $formFieldName; ?>" value="<?php echo $project->$property; ?>" />
    				<?php endif; ?>
    	    </div>
	    </div>
	    <?php
	}//function

	/**
	 * Wizard: Next - Previous
	 *
	 */
	public static function displayWizNextPrev()
	{
		$task = JRequest::getCmd('task');
		$num = intval(substr($task, strlen('wizard')));

		if($num > 1)
		{
			//...workaround cause first page is named 'wizard' - rename to 'wizard1' - to-do..
			$zNum =( $num == 2 ) ? '' : $num - 1;
		}
		?>
        <div id="wizard_control">
			<div class="button1-right">
				<div class="prev">
					<a onclick="submitbutton('wizard<?php echo $zNum; ?>');" title="<?php echo JText::_('Back'); ?>"><?php echo JText::_('Back'); ?></a>
				</div>
			</div>
			<div class="button1-left">
				<div class="next">
					<a onclick="submitbutton('wizard<?php echo ($num + 1); ?>');" title="<?php echo JText::_('Next'); ?>"><?php echo JText::_('Next'); ?></a>
				</div>
			</div>
		</div>
		<?php
	}//function

	/**
	 * replaces opening and closing tags with entities - nothing else..
	 *
	 * @param string $string
	 * @return string cleaned string
	 */
	public static function cleanHTML($string)
	{
		$cleaned = $string;
		$cleaned = str_replace('<', '&lt;', $cleaned);
		$cleaned = str_replace('>', '&gt;', $cleaned);

		return $cleaned;
	}//function

	    /**
     * Draws a project selector
     *
     * @return void
     */
    public static function drawProjectSelector()
    {
        $ecr_project = JRequest::getCmd('ecr_project');

        $projects = EasyProjectHelper::getProjectList();
        $projectTypes = EasyProjectHelper::getProjectTypes();

        echo NL.'<select style="font-size: 1.2em;" name="ecr_project" id="ecr_project" onchange="$(\'ecr_stat_project\').className = \'ajax_loading16\'; switchProject();">';
        echo NL.'<option value="">'.JText::_('Project').'...</option>';

        $selected =($ecr_project == 'ecr_new_project') ? ' selected="selected"' : '';
        $class = ' class="img3 icon-16-add"';
        echo NL.'<option'.$class.' value="ecr_new_project"'.$selected.'>'.JText::_('New Project').'</option>';

        $selected =($ecr_project == 'ecr_register_project') ? ' selected="selected"' : '';
        $class = ' class="img3 icon-16-install"';
        echo NL.'<option'.$class.' value="ecr_register_project"'.$selected.'>'.JText::_('Register Project').'</option>';

        foreach ($projectTypes as $comType => $display)
        {
            if(isset($projects[$comType])
            && count($projects[$comType]))
            {
                echo NL.'<optgroup label="'.$display.'">';

                foreach($projects[$comType] as $project)
                {
                    $selected =($project->fileName == $ecr_project) ? ' selected="selected"' : '';
                    $class = ' class="img12 icon-12-'.$comType.'"';
                    echo NL.'<option'.$class.' value="'.$project->fileName.'" label="'.$project->name.'"'.$selected.'>'.$project->name.'</option>';
                }//foreach

                echo NL.'</optgroup>';
            }
        }//foreach
        echo NL.'</select>';
    }// function



	public static function drawSelectScope($scope = '')
	{
	    if($scope)
	    {
	        echo JText::_('Scope').': <strong>'.$scope.'</strong>';
            echo '<input type="hidden" name="element_scope" value="'.$scope.'" />'.BR;

            return '';
	    }
?>
		<strong id="element_scope_label"><?php echo JText::_('Scope');?></strong>&nbsp;:
		<select name="element_scope" id="element_scope">
			<option value=""><?php echo JText::_('Select'); ?></option>
			<option value="admin"><?php echo JText::_('Admin'); ?></option>
			<option value="site"><?php echo JText::_('Site'); ?></option>
		</select>
		<br />
		<?php
		return 'element_scope';
	}//function

	public static function drawSelectName($name = '', $title = '')
	{
	    if( ! $title)
	    {
	        $title = JText::_('Name');
	    }

	    if($name)
	    {
	        echo '<div class="table_name">'.$title.' <big>'.$name.'</big></div>';
            echo '<input type="hidden" name="element_name" value="'.ucfirst($name).'" />';

            return '';
	    }
		?>
		<strong id="element_name_label"><?php echo $title; ?></strong>&nbsp;:
		<input type="text" id="element_name" name="element_name" value="" />
		<br />
		<?php
		return 'element_name';
	}

	/**
	 * Draw a submit button
	 *
	 * @param array $requireds required field names separated by komma
	 */
	public static function drawSubmitParts($requireds=array())
	{
		$requireds = (array)$requireds;
		$requireds = implode(',', $requireds);
		echo '<br />';
		echo '<div class="ecr_button img icon-16-save" onclick="newElement(\''.$requireds.'\');">'.JText::_('Save').'</div>';
	}

	/**
	 * Draw a submit button
	 *
	 * @param array $requireds required field names separated by komma
	 */
	public static function drawSubmitAutoCode($requireds=array())
	{
		$requireds = (array)$requireds;
		$requireds = implode(',', $requireds);
		echo '<br />';
		echo '<div class="ecr_button img icon-16-save" onclick="updateAutoCode(\''.$requireds.'\');">'.JText::_('Save').'</div>';
	}

	/**
	 * Displays a message with standard Joomla! backend css styles
	 * Type can be:
	 *
	 * 'notice'	: YELLOW
	 * 'error'	: RED
	 * '[EMPTY]': BLUE [default]
	 *
	 * @param array $messages
	 * @param string $type empty, notice, error
	 */
	public static function displayMessage($messages, $type = '')
	{
	    $callFile = '';

	    if(function_exists('debug_backtrace') && ECR_DEBUG)
	    {
    	    $trace = debug_backtrace();

    	    $callFile = str_replace(JPATH_COMPONENT.DS, '', $trace[0]['file']);
    	    $callFile .= ' ('.$trace[0]['line'].')';
	    }

		if( ! is_array($messages) )
		{
			$messages = array($messages);
		}
		?>
		<dl id="system-message">
			<dt class="<?php echo $type; ?>"><?php echo JText::_($type); ?></dt>
			<dd class="<?php echo $type; ?> message fade">
				<ul>
				<?php
				foreach($messages as $message)
				{
					echo '<li>'.$message.'</li>';
				}//foreach

				if($callFile)
				{
				    echo '<li><strong>'.$callFile.'</strong></li>';
				}
				?>
				</ul>
			</dd>
		</dl>
		<?php

		if($type == 'error' && ECR_DEBUG)
		{
		    self::printTrace();
		}
	}//function

	public static function printTrace()
	{
    	if ( ! function_exists('debug_backtrace')) return '';

	    $trace = debug_backtrace();

	    $s = '';
	    $s .= '<table border="1">';
	    $s .= '<tr>';
	    $s .= '<th>#</th><th>Function</th><th>File</th><th>Line</th><th>Args</th>';
	    $s .= '</tr>';

			for($i = count($trace) - 1; $i >= 0; --$i)
			{
			    $s .= '<tr>';
				$s .= '<td align="right"><tt>'.$i.'</tt></td>';
				$s .= '<td>';
					$s .=(isset( $trace[$i]['class'] )) ? $trace[$i]['class'] : '';
				    $s .=(isset( $trace[$i]['type'] )) ? $trace[$i]['type'] : '';
				$s .=(isset( $trace[$i]['function'] )) ? $trace[$i]['function'] : '';
				$s .= '</td>';
				    $s .=(isset( $trace[$i]['file'] )) ? '<td>'.str_replace(JPATH_ROOT.DS, '', $trace[$i]['file']).'</td>' : '<td>&nbsp;</td>';
				    $s .=(isset( $trace[$i]['line'] )) ? '<td align="right"><tt>'.$trace[$i]['line'].'</tt></td>' : '<td>&nbsp;</td>';

				$s .= '<td>';
				    				    if(isset($trace[$i]['args']))
				    {
				        foreach($trace[$i]['args'] as $arg)
				        {
				        	$s .= str_replace(JPATH_ROOT.DS, '', $arg).BR;
				        }//foreach
			#	    $s .=(isset( $trace[$i]['args'] )) ? '<td>'.implode(', ', $trace[$i]['args']).'</td>' : '<td>&nbsp;</td>';
				    }
				    else
				    {
				    }
				$s .= '</td>';

				$s .= '</tr>';
			}//for

			$s .= '</table>';

			echo $s;
	}//function

	/**
	 * Context menu
	 */
	public function contextMenu()
	{
		//--Add css
		ecrStylesheet('contextmenu');

		//--Add javascript
		ecrScript('contextmenu');

		$ajaxLink = 'index.php?option=com_easycreator';
		$ajaxLink .= '&controller=ajax&tmpl=component';
		$ajaxLink .= '&old_task='.JRequest::getCmd('task');
		$ajaxLink .= '&old_controller='.JRequest::getCmd('controller');
		$ajaxLink .= '&ecr_project='.$this->ecr_project;

		?>
		<script type="text/javascript">
			SimpleContextMenu.setup({'preventDefault':true, 'preventForms':false});
			SimpleContextMenu.attach('pft-file', 'CM1');
			SimpleContextMenu.attach('pft-directory', 'CM2');
		</script>

			<!-- Context menu files -->
			<?php
			$menuEntries = array(
				array(JText::_('New folder'), 'new_folder', 'add')
				, array(JText::_('New file'), 'new_file', 'add')
				, array(JText::_('Rename'), 'rename_file', 'rename')
				, array(JText::_('Delete'), 'delete_file', 'logout')
			);
			?>
		<ul id="CM1" class="SimpleContextMenu">
			<li class="title">
				<?php echo JText::_('File'); ?>
			</li>
			<?php
			foreach ($menuEntries as $menuEntry)
			{
				self::contextMenuEntry($ajaxLink, $menuEntry[0], $menuEntry[1], $menuEntry[2]);;
			}//foreach

			?>
		</ul>

			<!-- Context menu folders -->
			<?php
			$menuEntries = array(
				array(JText::_('New folder'), 'new_folder', 'add')
				, array(JText::_('New file'), 'new_file', 'add')
				, array(JText::_('Rename'), 'rename_folder', 'rename')
				, array(JText::_('Delete'), 'delete_folder', 'logout')
			);
			?>
		<ul id="CM2" class="SimpleContextMenu">
			<li class="title">
				<?php echo JText::_('Folder'); ?>
			</li>
			<?php
			foreach ($menuEntries as $menuEntry)
			{
				self::contextMenuEntry($ajaxLink, $menuEntry[0], $menuEntry[1], $menuEntry[2]);;
			}//foreach

			?>
		</ul>

		<input type="hidden" name="act_folder" id="act_folder" />
		<input type="hidden" name="act_file" id="act_file" />
		<?php
	}//function

	private static function contextMenuEntry($ajaxLink, $title, $task, $icon)
	{
		?>
		<li>
			<a class="modal" onclick="SimpleContextMenu._hide();"
				 rel="{handler: 'iframe', size: {x: 600, y: 150}}"
				 href="<?php echo $ajaxLink.'&task='.$task; ?>">
				<span class="img icon-16-<?php echo $icon; ?>">
					<?php echo JText::_($title)?>
				</span>
			</a>
		</li>
		<?php
	}//function

	/**
	 *
	 * @param $ac
	 * @param $newIndent
	 * @return unknown_type
	 */
	public static function idt($ac = '', $newIndent = 0)
	{
		static $indent = 0;
		if( $newIndent )
		{
			$indent = $newIndent;
		}
		if($ac == '-') { $indent --; }
		$i = NL.str_repeat('   ', $indent);
		if($ac == '+') { $indent ++; }
		return $i;
	}//function

    /**
     * converts a bytevalue into the highest possible unit and adds it's sign.
     * @version  2009-01-27 03:50h
     *
     * @param    bigint|float  $bytes    -bytevalue to convert
     * @param    int           $exp_max  -maximal allowed exponent (0='B', 1='KB', 2='MB', ...)
     *
     * @return   string
     */
    public static function byte_convert($bytes, $exp_max = null)
    {
        $symbols = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

        $exp = 0;

        if($exp_max === null)
        {
            $exp_max = count($symbols)-1;
        }

        $converted_value = 0;

        if($bytes > 0)
        {
            $exp = floor( log($bytes)/log(1024) );
            if( $exp > $exp_max ) $exp = $exp_max;
            $converted_value = ( $bytes/pow(1024,$exp) );
        }

        return number_format($converted_value,2,',','.').' '.$symbols[$exp];
    }//function

    public static function boxStart()
    {
?>
    <div class="q">
        <div class="q">
            <div class="q"></div>
        </div>
    </div>
    <div class="s">
<?php
    }//function

    public static function floatBoxStart()
    {
?>
<div class="ecr_floatbox">
<?php
    	self::boxStart();
    }//function

    public static function floatBoxEnd()
    {
        self::boxEnd();
?>
</div>
<?php
    }//function

    public static function boxEnd()
    {
        ?>
    </div>
    <div class="w">
        <div class="w">
            <div class="w"></div>
        </div>
    </div>
<?php
    }//function

}// class

class EasyTemplateInfo
{
    public $group = '';
	public $title = '';
	public $description = '';

	function info()
	{
	    $ret = '';
        $ret .= '<div style="color: blue; font-weight: bold; text-align:center;">'.ucfirst($this->group).' - '.$this->title.'</div>';
        $ret .= '<div style="color: orange; font-weight: bold;">'.$this->description.'</div>';

        return $ret;
	}//function

	public function format($format, $type = 'new')
	{
	    $ret = '';
        $ret .= '<span class="img icon-16-'.$type.'">';
	    switch ($type)
	    {
	    	case 'edit':
	    	  $ret .= JText::_('Edit');
	    	break;

	    	case 'add':
              $ret .= JText::_('New');
	    	break;

	    	default:
	    		;
	    	break;
	    }//switch

	    $ret .= '</span>';

	    switch ($format)
	    {
	    	case 'erm':
                $ret .= '<div style="color: blue; font-weight: bold; text-align:center;">'.ucfirst($this->group).' - '.$this->title.'</div>';
                $ret .= '<div style="color: orange; font-weight: bold;">'.$this->description.'</div>';
	    	break;

	    	default:
	    		return JText::sprintf('Undefined format: %s', $format);
	    	break;
	    }//switch

        return $ret;
    }//function

    public static function error($message)
    {
    	echo $message.' in '.get_parent_class($this);
    	var_dump(debug_print_backtrace());
    }//function

}//class
